package com.yy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yy.domain.AppointmentTasksDO;
import com.yy.domain.PatientExaminationDO;
import com.yy.dao.PatientExaminationMapper;
import com.yy.service.PatientExaminationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yy.vo.AppointmentTasksPageVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 患儿检查信息表 服务实现类
 * </p>
 *
 * @author 姚欣宏
 * @since 2024-04-12
 */
@Service
public class PatientExaminationServiceImpl extends ServiceImpl<PatientExaminationMapper, PatientExaminationDO> implements PatientExaminationService {

    @Override
    @Transactional
    public Integer insertEvaluate(PatientExaminationDO patientEvaluationVO) {
        Date examinationDate = patientEvaluationVO.getExaminationDate();
        String patientRegistrationNumber = patientEvaluationVO.getPatientRegistrationNumber();
        String contactPhone = patientEvaluationVO.getContactPhone();
        LocalDate examinationDateOnly = examinationDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        Date truncatedDate = Date.from(examinationDateOnly.atStartOfDay(ZoneId.systemDefault()).toInstant());
        // 检查日期查询记录如果有六条，则当天不能预约了，返回code=100
        int countByExaminationDate = baseMapper.countByExaminationDate(truncatedDate);
        if (countByExaminationDate >= 6) {
            return 100;
        }
        // 检查当前时间，如果预约的是今天且当前时间在19:00之后（包括19:00），则不能预约，返回code=300 如果不是今天 则不用这个判断
        if (isToday(examinationDate) && isAfter1900(new Date())) {
            // 当前时间已经超过或等于19:00
            return 300;
        }

        // 获取当前日期和时间
        ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
        LocalDate currentDate = now.toLocalDate();
        LocalTime currentTime = now.toLocalTime();

        LocalDate startDate;
        if (currentTime.isBefore(LocalTime.of(16, 0)) || currentTime.equals(LocalTime.of(16, 0))) {
            // 当前时间在19点之前（包括19点），查询今天及之后的日期
            startDate = currentDate;
        } else {
            // 当前时间在19点之后，查询明天的日期开始
            startDate = currentDate.plusDays(1);
        }

        String startDateStr = startDate.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        int countByPatientRegistrationNumberAndContactPhone = baseMapper.countByPatientRegistrationNumberAndContactPhoneAndExaminationDate(patientRegistrationNumber, contactPhone, startDateStr);
        if (countByPatientRegistrationNumberAndContactPhone > 0) {
            return 400;
        }

        // 其他情况就可以预约，保存记录，返回code=200
        save(patientEvaluationVO);
        return 200;
    }

    @Override
    public PatientExaminationDO getLatestByRegistrationAndPhone(String patientRegistrationNumber, String contactPhone) {
        QueryWrapper<PatientExaminationDO> wrapper = new QueryWrapper<>();
        wrapper.eq("patient_registration_number", patientRegistrationNumber);
        wrapper.eq("contact_phone", contactPhone);
        wrapper.orderByDesc("id"); // 按照id逆序排序
        wrapper.last("LIMIT 1"); // 限制返回的记录数为1
        List<PatientExaminationDO> results = baseMapper.selectList(wrapper);
        if (results != null && !results.isEmpty()) {
            return results.get(0); // 返回列表中的第一条记录，也就是id最大的那条记录
        } else {
            return null; // 如果没有找到记录，则返回null
        }
    }

    @Override
    public List<PatientExaminationDO> getExaminationDate(String examinationDate) {
        QueryWrapper<PatientExaminationDO> wrapper = new QueryWrapper<>();
        wrapper.eq("examination_date", examinationDate);
        wrapper.orderByDesc("id");
        List<PatientExaminationDO> results = baseMapper.selectList(wrapper);
        return results;
    }

    @Override
    public PageInfo<PatientExaminationDO> getList(AppointmentTasksPageVO appointmentTasksPageVO) {
        PageHelper.startPage(appointmentTasksPageVO.getPageNum(), appointmentTasksPageVO.getPageSize());
        QueryWrapper<PatientExaminationDO> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(appointmentTasksPageVO.getAppointmentDate()), "examination_date", appointmentTasksPageVO.getAppointmentDate()).like(StringUtils.isNotBlank(appointmentTasksPageVO.getAppointmentPhone()), "contact_phone", appointmentTasksPageVO.getAppointmentPhone()).orderByDesc("examination_date");
        List<PatientExaminationDO> patientExaminationDOS = list(wrapper);
        PageInfo<PatientExaminationDO> pageInfo = new PageInfo(patientExaminationDOS);
        return pageInfo;
    }

    @Override
    public void delete(Integer id) {
        removeById(id);
    }

    private boolean isToday(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        calendar.setTime(new Date()); // 使用当前时间
        int currentYear = calendar.get(Calendar.YEAR);
        int currentMonth = calendar.get(Calendar.MONTH);
        int currentDay = calendar.get(Calendar.DAY_OF_MONTH);

        return year == currentYear && month == currentMonth && day == currentDay;
    }

    private boolean isAfter1900(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        return hour >= 16;
    }
}
